package com.bto.solar.work.controller;

import com.bto.solar.work.aliyunsms.SmsService;
import com.bto.solar.work.common.BizLoginException;
import com.bto.solar.work.common.R;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.dto.ApiLoginReq;
import com.bto.solar.work.dto.ApiLoginRes;
import com.bto.solar.work.service.BtoLoginService;
import com.bto.solar.work.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@CrossOrigin
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private BtoLoginService btoLoginService;
    @Autowired
    private SmsService smsService;

    @PostMapping("")
    public R<ApiLoginRes> login(@Valid @RequestBody ApiLoginReq apiLoginReq) {
        return R.ok(btoLoginService.apiLogin(apiLoginReq));
    }

    @PostMapping("/web")
    public R<ApiLoginRes> loginByWeb(@Valid @RequestBody ApiLoginReq apiLoginReq) {
        return R.ok(btoLoginService.apiLoginByWeb(apiLoginReq));
    }
    
    @PostMapping("/refresh")
    public R<String> getRefreshToken (
            @RequestParam("refreshToken") String refreshToken
    ) {
        String accessToken = btoLoginService.getToken(refreshToken);
        if (StringUtils.isNotEmpty(accessToken)) {
            return R.ok(accessToken);
        } else {
            throw new BizLoginException(401, "请重新登陆！");
        }
    }

    @PostMapping("/send-sms")
    public R<String> getSmsCode (@RequestParam(value = "phone") String phone) {
        smsService.getSmsCode(phone, Constants.LOGIN);
        return R.ok("验证码已发送！验证码有效为5分钟");
    }

    @PostMapping("/out")
    public R<String> loginOut() {
        boolean loginOut = btoLoginService.loginOut();
        if (loginOut) {
            return R.ok("系统退出成功！");
        } else {
            return R.fail("系统退出失败！");
        }
    }



}
